#include <iostream>
#include <string>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void print(const std::string &str)
{

}

void http_callback(wsserver_t *srv, websocketpp::connection_hdl hdl) {
    wsserver_t::connection_ptr conn=srv->get_con_from_hdl(hdl);
   //request_type const & get_request();获取请求对象
    websocketpp::http::parser::request req =conn->get_request();
    std::string url=req.get_uri();
    std::string body=req.get_body();
    std::string method=req.get_method();
    
    std::cout<<"url: "<<url<<std::endl;
    std::cout<<"method: "<<method<<std::endl;
    std::cout<<"body: "<<body<<std::endl;

     std::string response_body = "<html><body><h1>Hello World</h1></body></html>";
     conn->set_body(response_body);//设置响应正文
     conn->append_header("Content-Type", "text/html");//设置响应报头
     conn->set_status(websocketpp::http::status_code::ok);//设置状态行



    
  
}
void wsopen_callback(wsserver_t *srv, websocketpp::connection_hdl hdl) {
  std::cout<<"websock握手成功"<<std::endl;
  
}
void wsclose_callback(wsserver_t *srv, websocketpp::connection_hdl hdl) {
    std::cout<<"websocket握手失败"<<std::endl;
}
void wsmsg_callback(wsserver_t *srv, websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg) {
    wsserver_t::connection_ptr conn=srv->get_con_from_hdl(hdl);
   std:: string request=msg->get_payload();
   std::cout<<"client said: "<<request<<std::endl;
   std:: string response ="hhhhhhhhhhhhhhhhh";
   conn->send(response);
   


}
int main()
{
    //1. 实例化server对象
    wsserver_t server;
   
    //2. 设置日志等级
    server.set_access_channels(websocketpp::log::alevel::none);
   
    //3. 初始化asio调度器
    server.init_asio();
    server.set_reuse_addr(true);
    
    //4. 设置回调函数
    server.set_http_handler(std::bind(&http_callback,&server,std::placeholders::_1));
    server.set_open_handler(std::bind(&wsopen_callback,&server,std::placeholders::_1));
    server.set_close_handler(std::bind(&wsclose_callback,&server,std::placeholders::_1));
    server.set_message_handler(std::bind(&wsmsg_callback,&server,std::placeholders::_1,std::placeholders::_2));    
    //5. 设置监听端口
    server.listen(8888);
   
    //6. 开始获取新连接
    server.start_accept();
   
    //7. 启动服务器
    server.run();
    
    return 0;
}